<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱地址" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:channel:school:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:channel:school:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:channel:school:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="用户ID" align="center" prop="userId"/>
      <el-table-column label="角色" align="center" prop="userType">
        <template slot-scope="{row}">
          <span v-if="row.userType === '01'">管理员</span>
          <span v-else-if="row.userType === '10'">一级代理商</span>
          <span v-else-if="row.userType === '11'">二级代理商</span>
          <span v-else-if="row.userType === '12'">三级代理商</span>
          <span v-else-if="row.userType === '20'">学校</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="userName"/>
      <el-table-column label="手机号" align="center" prop="phonenumber"/>
      <el-table-column label="邮箱" align="center" prop="email"/>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                     @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="权限说明" align="center">
        <template slot-scope="{row}">
          <span v-if="row.userType === '01'">代理商账号管理、学校账号管理、学生账号管理</span>
          <span v-else-if="row.userType === '10' || row.userType === '11' || row.userType === '12'">学校账号管理、学生账号管理</span>
          <span v-else-if="row.userType === '20'">学生账号管理</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:channel:school:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:channel:school:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleResetPassword(scope.row)"
            v-hasPermi="['system:channel:school:password']"
          >重置密码
          </el-button>
          <el-button
            v-if="userType === '20'"
            size="mini"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['system:channel:school:query']"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改渠道对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="角色">
          学校
        </el-form-item>
        <el-form-item label="上级代理商" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择上级代理商员" :disabled="formStatus === '1'">
            <el-option v-for="item in agentUserList" :key="item.userId" :value="item.userId" :label="item.userName"/>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱地址"/>
        </el-form-item>
        <el-form-item v-if="formStatus === '0'" label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码"/>
        </el-form-item>


        <el-form-item v-if="form.userType" label="权限说明">
          <span v-if="form.userType === '01'">代理商账号管理、学校账号管理、学生账号管理</span>
          <span
            v-else-if="form.userType === '10' || form.userType === '11' || form.userType === '12'">学校账号管理、学生账号管理</span>
          <span v-else-if="form.userType === '20'">学生账号管理</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改渠道对话框 -->
    <el-dialog title="详情" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="150px">
        <el-form-item label="上级代理商：">
          {{form.parentName || ''}}
        </el-form-item>
        <el-form-item label="上级代理商-手机号：">
          {{form.parentPhone || ''}}
        </el-form-item>
        <el-form-item label="角色：">
          学校
        </el-form-item>
        <el-form-item label="名称：" prop="userName">
          {{form.userName || ''}}
        </el-form-item>
        <el-form-item label="手机号：" prop="phonenumber">
          {{form.phonenumber || ''}}
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          {{form.email || ''}}
        </el-form-item>


        <el-form-item v-if="form.userType" label="权限说明：">
          学生账号管理
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="resetPwdShow" width="600px" append-to-body>
      <el-form ref="form" :model="resetPwdForm" :rules="resetPwdFormRules" label-width="120px">
        <el-form-item label="密码" prop="password">
          <el-input v-model="resetPwdForm.password" placeholder="请输入最新密码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitRestPassword">确 定</el-button>
        <el-button @click="resetPwdShow=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listChannelUser, getChannelUser, delChannelUser, addChannelUser, updateChannelUser,
  resetPasswordChannelUser, changeUserStatus
} from "@/api/system/channel-school"
import {listAllChannelUser} from "@/api/system/channel"
import {mapGetters} from "vuex";

export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 渠道表格数据
      userList: [],
      // 代理商用户列表
      agentUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userType: null,
        pid: null,
        userName: null,
        phonenumber: null,
        email: null,
        password: null,
        status: null,
        loginIp: null,
        loginDate: null,
        pwdUpdateDate: null,
      },
      // 表单参数
      form: {},
      // 表单状态 0=新增 1=修改 2=查看
      formStatus: '',
      // 表单校验
      rules: {
        userType: [
          {required: true, message: "角色不能为空", trigger: "change"}
        ],
        parentId: [
          {required: true, message: "上级不能为空", trigger: "change"}
        ],
        userName: [
          {required: true, message: "名称不能为空", trigger: "change"}
        ],
        phonenumber: [
          {required: true, message: "手机号不能为空", trigger: "change"}
        ],
        email: [
          {required: true, message: "邮箱不能为空", trigger: "change"}
        ],
        password: [
          {required: true, message: "密码不能为空", trigger: "change"}
        ],
      },

      resetPwdShow: false,
      resetPwdForm: {
        userId: undefined,
        password: ''
      },
      resetPwdFormRules: {
        password: [
          {required: true, message: "密码不能为空", trigger: "change"}
        ]
      },

      viewOpen: false
    }

  },
  computed: {
    ...mapGetters(["userType"])
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询渠道列表 */
    getList() {
      this.loading = true
      listChannelUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })

      this.getAllChannelUserList()
    },
    getAllChannelUserList() {
      listAllChannelUser().then(res => {
        if (res.code === 200) {
          const data = res.data || []
          this.agentUserList = data.filter(item => item.userType === '12') || []
        }
      })
    },
    handleUserTypeChange() {
      this.form.parentId = undefined
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        userType: null,
        userName: null,
        phonenumber: null,
        parentId: null,
        email: null,
        password: null,
        status: null,
        delFlag: null,
        loginIp: null,
        loginDate: null,
        pwdUpdateDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.formStatus = '0'
      this.open = true
      this.title = "添加渠道"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const userId = row.userId || this.ids
      getChannelUser(userId).then(response => {
        this.form = response.data
        this.formStatus = '1'
        this.open = true
        this.title = "修改渠道"
      })
    },
    handleView(row) {
      this.reset()
      const userId = row.userId || this.ids
      getChannelUser(userId).then(response => {
        this.form = response.data
        this.formStatus = '2'
        this.viewOpen = true
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateChannelUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addChannelUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids
      this.$modal.confirm('是否确认删除渠道编号为"' + userIds + '"的数据项？').then(function () {
        return delChannelUser(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
        return changeUserStatus(row.userId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    handleResetPassword(row) {
      this.resetPwdForm = {
        userId: row.userId,
        password: ''
      }
      this.resetPwdShow = true
    },
    onSubmitRestPassword() {
      resetPasswordChannelUser({
        userId: this.resetPwdForm.userId,
        password: this.resetPwdForm.password
      }).then(response => {
        this.getList()
        this.resetPwdShow = false
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
